package com.cj.myblog.common.util;

import com.cj.myblog.constants.Constants;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * Created by jujunchen on 2017/10/6.
 */
public class SendMail implements Runnable {

    private static Map<String,Object> map =  Constants.options;

    private Map<String,String> toMap;

    public SendMail(Map<String, String> toMap) {
        this.toMap = toMap;
    }

    @Override
    public void run() {

        JavaMailSenderImpl mailSender  = new JavaMailSenderImpl();
        mailSender.setHost(map.get("mailServer").toString());
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            mimeMessageHelper.setTo(toMap.get("to"));
            mimeMessageHelper.setFrom(map.get("mailUser").toString());
            mimeMessageHelper.setSubject(toMap.get("subject"));
            mimeMessageHelper.setText(StrUtil.format(map.get("mailTpl").toString(),toMap.get("url")),true);

            mailSender.setUsername(map.get("mailUser").toString());
            mailSender.setPassword(map.get("mailPassword").toString());

            Properties prop = new Properties() ;
            // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
            prop.put("mail.smtp.auth", "true") ;
            prop.put("mail.smtp.timeout", "25000") ;
            mailSender.setJavaMailProperties(prop);
            //发送邮件
            mailSender.send(mimeMessage);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }



}
